package com.pureland.ucc.service.impl;

import com.pureland.security.entity.AuthInfo;
import com.pureland.security.exceptions.InvalidException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @projectName: pureland_cloud
 * @className: com.pureland.ucc.service.impl.UserService
 * @description: 认证与授权实现
 * @author: tong.li
 * @createTime: 2020/11/18 13:59
 * @version: v1.0
 * @copyright: 版权所有 李彤 © 2020
 */
@Service
public class UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    static Map<String,UserDetails> users = null;
    static {
        users = new ConcurrentHashMap<>();
        AuthInfo build = AuthInfo.builder()
                .username("admin")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .enabled(true)
                .build();
        users.put("admin",build);
    }

    /**
     * 账户密码登录逻辑实现
     * @param username
     * @return
     */
    public UserDetails loadUserByPassword(String username, String password) {
        if (StringUtils.isEmpty(username)) {
            throw new InvalidException("用户名不合法");
        }
        if (StringUtils.isEmpty(password)) {
            throw new InvalidException("密码不合法");
        }
        if (!users.containsKey(username)) {
            throw new InvalidException("用户不存在");
        }
        if ("admin".equals(username) && "123456".equals(password)) {
            return AuthInfo.builder()
                    .username(username)
                    .password(passwordEncoder.encode("123456"))
                    .build();
        } else {
            throw new InvalidException("用户名密码错误");
        }

    }



    /**
     * 短信验证码登录逻辑实现
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserBySms(String username,String smsCode) throws InvalidException {
        // 校验短信验证码
        if (StringUtils.isEmpty(smsCode) || !"1111".equals(smsCode)) {
            throw new InvalidException("短信验证码错误");
        }
        if (StringUtils.isEmpty(username)) {
            throw new InvalidException("用户名不合法");
        }
        if (!users.containsKey(username)) {
            throw new InvalidException("用户不存在");
        }
        // 短信校验成功后表示登录成功
        return AuthInfo.builder()
                .username(username)
                .roles(Collections.emptyList())
                .build();
    }

}
